import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:gameplay_flutter/lib_baseview/theme/jr.dart';
import 'package:gameplay_flutter/lib_runtime/extension/string_extension/string_text.dart';
import 'package:gameplay_flutter/lib_runtime/extension/widget/widget_wrapper.dart';

import '../../../../../../lib_basemodel/chat_room/chat/chat_content.dart';
import '../../../../../../lib_basemodel/chat_room/chat/hb_rtm_message_type.dart';
import '../../../../../../lib_basemodel/chat_room/chat/show_item.dart';
import '../../../../../../lib_basemodel/chat_room/habibi-msg/hb_rtm_message_detail_type.dart';
import '../../../../../../lib_basemodel/chat_room/habibi-msg/hb_rtm_msg.dart';
import '../../../../../../lib_baseview/lib_baseview.dart';

///
/// 这里展示的消息的内容
///
class ShowItemsWidget extends StatelessWidget {
  final ChatContent? chatContent;
  final HbRtmMsg? rtmMsg;

  const ShowItemsWidget({Key? key, this.chatContent, this.rtmMsg})
      : super(key: key);

  // InlineSpan _buildContentItem(BuildContext context, ShowItem item) {
  //   switch (item.style) {
  //     case ItemStyle.icon:
  //       return _buildIconItem(item);
  //     case ItemStyle.link:
  //       return _buildLinkItem(context, item);
  //     case ItemStyle.text:
  //       return _buildTextItem(item);
  //     case ItemStyle.emote:
  //       return WidgetSpan(child: _EmoteItem(message: item));
  //     case ItemStyle.gradient:
  //       return _buildGradientItem(context, item);

  //     default:
  //       return _buildTextItem(item);
  //   }
  // }

  // InlineSpan _buildIconItem(ShowItem item) {
  //   return WidgetSpan(
  //     alignment: PlaceholderAlignment.middle,
  //     child: item.url == null
  //         ? SizedBox()
  //         : CachedNetworkImage(
  //             imageUrl: item.url!, fit: BoxFit.fitWidth,
  //             width:
  //                 ((item.size ?? 0).toInt() == 0 ? 28 : (item.size ?? 0)) * 1.0,
  //             // height: (item.size.toInt() == 0 ? 28 : item.size.toInt())*1.0,
  //           ),
  //   );
  // }

  // InlineSpan _buildTextItem(ShowItem item) {
  //   try {
  //     Map? extra = json.decode(item.extra ?? '');
  //     if (extra != null) {
  //       if (extra['type'] == 'emote') {
  //         return WidgetSpan(child: _EmoteItem(message: item));
  //       }
  //     }
  //   } catch (e) {}
  //   RegExp exp = RegExp(r'^[\ue601-\ue62e]+$');
  //   bool isEmoji = exp.hasMatch(item.text ?? '');
  //   if (isEmoji) {
  //     return WidgetSpan(
  //         child: IntrinsicWidth(
  //       child: Container(
  //           alignment: Alignment.center,
  //           constraints:
  //               BoxConstraints(maxWidth: ScreenUtils.ins.screenWidth - 2 * 68),
  //           child: Text(item.text ?? '',
  //               maxLines: 8,
  //               style: const TextStyle(
  //                 letterSpacing: 1.5,
  //                 fontSize: 28,
  //                 height: 1.2,
  //               ).withEmoji)),
  //     ));
  //   } else {
  //     return TextSpan(
  //       text: item.text,
  //       style: TextStyle(
  //         fontSize: (item.size ?? 0) > 0 ? (item.size ?? 0) * 1.0 : 12,
  //         fontWeight: ((item.weight ?? 0) > 0 &&
  //                 (item.weight ?? 0) <= FontWeight.values.length)
  //             ? FontWeight.values[(item.weight ?? 0) - 1]
  //             : null,
  //         color: parseColor(item.color),
  //       ).withEmoji,
  //     );
  //   }
  // }

  // Color parseColor(dynamic color, {Color defColor = Colors.white}) {
  //   if (color == null || color.isEmpty) return defColor;
  //   String colorStr = color as String;
  //   String resultStr = '';

  //   if (colorStr.length >= 8) {
  //     resultStr = '0x${color.safeSubstring(color.length - 8)}';
  //   } else {
  //     resultStr = '0xff${color.safeSubstring(color.length - 6)}';
  //   }
  //   try {
  //     return Color(int.parse(resultStr));
  //   } catch (e) {
  //     return defColor;
  //   }
  // }

  // InlineSpan _buildLinkItem(BuildContext context, ShowItem item) {
  //   return TextSpan(
  //       text: item.text,
  //       style: TextStyle(
  //         fontSize: (item.size ?? 0) > 0 ? (item.size ?? 0) * 1.0 : 12,
  //         color: parseColor(item.color, defColor: const Color(0xffffd400)),
  //       ),
  //       recognizer: TapGestureRecognizer()
  //         ..onTap = () {
  //           // String url = item.url.replaceAll('yqdf.xyz/', '');
  //           // SchemeHelper.checkAndGo(context, url);
  //         });
  // }

  // InlineSpan _buildGradientItem(BuildContext context, ShowItem item) {
  //   return WidgetSpan(
  //     alignment: PlaceholderAlignment.middle,
  //     child: Container(
  //       clipBehavior: Clip.antiAlias,
  //       // decoration: decoration,
  //       child: CustomPaint(
  //         painter: JRGradientPainter(LinearGradient(
  //           colors: JR.color.brandGradient,
  //           begin: AlignmentDirectional.bottomStart,
  //           end: AlignmentDirectional.topEnd,
  //         )),
  //         child: (item.text ?? '').text(color: Colors.red, fontSize: 12),
  //       ),
  //     ),
  //   );
  // }

  // List<InlineSpan>? _createSpanList(BuildContext context) {
  //   print('');
  //   return items?.map((_) => _buildContentItem(context, _!)).toList();
  // }

  @override
  Widget build(BuildContext context) {
    // HBMessageType? type;
    if (rtmMsg?.rtmType == HBRtmMessageType.rtmSmallMessageTypeReward) {
      return giftMsgWidget;
    } else if (rtmMsg?.rtmType ==
        HBRtmMessageType.rtmSmallMessageTypeUserJoin) {
      return userJoinWidget;
    }

    return textWidget;
  }

  /// 用户进入消息
  Widget get userJoinWidget {
    return Stack(
      children: [
        JR.img('room/room_user_join_bg.png',
            width: 173, height: 20, fit: BoxFit.contain),
        Row(
          children: [
            '${rtmMsg?.msg?.nickName}'
                .text(color: const Color(0xFFFFFFFF), fontSize: 12)
                .padding(start: 9, end: 8),
            '${rtmMsg?.msg?.message}'
                .text(color: Color(0xFFFFFFFF), fontSize: 12),
          ],
        ),
      ],
    );
  }

  /// 礼物消息
  Widget get giftMsgWidget {
    return IntrinsicWidth(
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            // 接收者昵称
            if (rtmMsg?.msg?.receiveNickName != null)
              ConstrainedBox(
                constraints: const BoxConstraints(maxWidth: 200),
                child: Text(
                  rtmMsg?.msg?.receiveNickName ?? '',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 12,
                    overflow: TextOverflow.ellipsis,
                  ),
                  maxLines: 1,
                ),
              ),

            const SizedBox(height: 8),

            Row(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                if (rtmMsg?.msg?.objectUrl != null)
                  Container(
                    width: 40,
                    height: 50,
                    margin: const EdgeInsetsDirectional.only(end: 4),
                    child: JR.img(
                      '${rtmMsg?.msg?.objectUrl}',
                      fit: BoxFit.contain,
                    ),
                  ),
                const SizedBox(width: 4),
                'x'.text(
                    color: Colors.white,
                    fontSize: 18,
                    weight: TextFontWeight.bold),
                const SizedBox(width: 4),
                ('${rtmMsg?.msg?.giftCount ?? 0}').text(
                    color: Colors.white,
                    fontSize: 26,
                    weight: TextFontWeight.medium),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 普通文本
  Widget get textWidget {
    if (rtmMsg?.msg?.message == null) {
      return const SizedBox();
    }

    final safeMsg = rtmMsg?.msg?.messageType == HBRtmMessageDetailType.safeMsg;

    final textSpan = TextSpan(
      text: rtmMsg?.msg?.message,
      style: TextStyle(
        color: safeMsg ? const Color(0xFFEFD298) : Colors.white,
        fontSize: 14,
        fontWeight: TextFontWeight.regular.toFontWeight,
        fontFamily: TextFontFamily.harmonyOS.family,
      ),
    );

    final textPainter = TextPainter(
      text: textSpan,
      textDirection: TextDirection.ltr,
    )..layout();

    double width = textPainter.width + 5;
    if (width > 250) {
      width = 250;
    }

    return SizedBox(
      width: width,
      child: Text(
        rtmMsg?.msg?.message ?? '',
        softWrap: true,
        style: TextStyle(
          color: safeMsg ? const Color(0xFFEFD298) : Colors.white,
          fontSize: 14,
          fontWeight: TextFontWeight.regular.toFontWeight,
          fontFamily: TextFontFamily.harmonyOS.family,
        ),
      ),
    );
  }
}

class _EmoteItem extends StatelessWidget {
  final ShowItem message;

  const _EmoteItem({super.key, required this.message});

  @override
  Widget build(BuildContext context) {
    String? url = emoteUrl;
    if (url == null || url.isEmpty) {
      return const SizedBox.shrink();
    }
    return image(url, width: 65, fit: BoxFit.fitWidth);
  }

  String? get emoteUrl {
    try {
      Map? extra = json.decode(message.extra ?? '');
      if (extra != null) {
        Map? emote = extra['emote'];
        return emote?['url'];
      }
    } catch (e) {}
    return null;
  }
}
